package com.example.testdemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockReadWrite {

    private ReadWriteLock  rwlock=new ReentrantReadWriteLock();

    private Lock rlock= rwlock.readLock();
    private  Lock wlock=rwlock.writeLock();


    public  void write(){
        try {

            wlock.lock();
            System.out.println(Thread.currentThread().getName()+"写进程：enter");
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"写进程：leave");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            wlock.unlock();
        }
    }

    public  void read(){
        try {

            rlock.lock();
            System.out.println(Thread.currentThread().getName()+"读进程：enter");
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"读进程：leave");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rlock.unlock();
        }
    }
}

class  TestDemo{
    public static void main(String[] args) {
        LockReadWrite rwlock=new LockReadWrite();

        for(int i=0;i<5;i++){
            new Thread(()->{
//                rwlock.read();           //共享锁           一次允许多个进程进入

                rwlock.write();     //排它锁        只有每个线程执行完毕才能 执行下一个
            }).start();
        }
    }
}
